const {searchUser} = require('../../service/login/loginSer')
const {sign} = require('../../config/jwt')
const passwordCon = require('../../utils/bcryptPassword')

class LoginCon {
    async login(ctx) {
        const {password, userNumber} = ctx.request.body
        // 判读账号密码是否为空
        if (!password || !userNumber) {
            return ctx.body = {
                code: '999',
                message: '账号或密码不能为空'
            }
        }
        try {
            const user = await searchUser({userNumber})
            if (user.length === 0) {
                return ctx.body = {
                    code: '999',
                    message: '账号不存在'
                }
            }
            const isOk = passwordCon.decode(password, user[0].dataValues.password)
            if (!isOk) {
                return ctx.body = {
                    code: '999',
                    message: '密码错误'
                }
            } else {
                if (user[0].dataValues.userBlacklist === '1') {
                    ctx.body = {
                        code: '999',
                        message: '该用户已被拉黑，无法登录！'
                    }
                } else {
                    const token = sign({
                        userNumber: user[0].dataValues.userNumber,
                        userName: user[0].dataValues.userName
                    })
                    ctx.body = {
                        code: '200',
                        data: {
                            user: user[0],
                            token: token,

                        }
                    }
                }
            }
        } catch (e) {
            ctx.app.emit('error', e.toString(), ctx)
        }


    }
}

module.exports = new LoginCon()
